WebSocket = window.WebSocket || window.MozWebSocket;
if( !WebSocket ) {
	var wsobg = {};
	var ws_ready = false;
	$(window).load(function(){
		ws_ready = true;
	});
	$(function(){		
		$.ajax({
			url: WS_STATIC_URL + '/jquery.swfobject.js',
			dataType: 'script',
			async: false,
			cache: true
		});
		
		window.WebSocket = function( a ) {
			a = a.match( /wss{0,1}\:\/\/([0-9a-z_.-]+)(?:\:(\d+)){0,1}/i );
			this.host = a[1];
			this.port = a[2] || 843;
			this.onopen = function(){}
			this.onclose = function(){}
			this.onmessage = function(){}
			this.onerror = function(){}
			this.ready = function(b){
				return true;
			}
			this.send = function(b){
				return wsobg.call.Send(b);
			}
			this.close = function(){
				return wsobg.call.Close();
			}
			this.ping = function(){
				return wsobg.call.Ping();
			}
			this.connect = function(){
				wsobg.call = $('#flash_websocket')[0];
				wsobg.call.Connect( this.host,this.port );
			};
			if ( $('#websocket').size() ) {
				this.connect();
			} else {
				
				var div = $('<div></div>').attr({id:'websocket'}).css({position:'absolute', top:-999, left:-999});
				div.flash({
					swf: WS_STATIC_URL +'/websocket/websocket.swf',
					wmode: "window",
					scale: "showall",
					allowFullscreen : true,
					allowScriptAccess : 'always',
					id: 'flash_websocket',
					width : 1,
					height : 1,
					flashvars : { call: 'wsobg._this' }
				});
				$('body').append(div);
			}
			wsobg._this = this;
		}
	});
}

$(function($) {
	$.ws = { obg: {}, message: {}, open:[], close:[], status: false, link:function(){} };
	
	// 添加消息回调函数 1 参数 消息 keys 2参数 回调函数
	$.wsmessage = function( k, f ) {
		if ( !k || !$.isFunction( f ) ) {
			return false;
		}
		$.ws.message[k] = $.ws.message[k] || [];
		$.ws.message[k].push(f);
	};
	
	// 注册 打开回调函数
	$.wsopen = function( f ) {
		if ( !$.isFunction( f ) ) {
			return false;
		}
		$.ws.open.push(f);
	};
	
	// 注册 关闭回调函数
	$.wsclose = function( f ) {
		if ( !$.isFunction( f ) ) {
			return false;
		}
		$.ws.close.push(f);
	};
	
	// 注册 发送信息
	$.wssend = function( d ) {
		return $.ws.status && $.ws.obg.send(d);
	};
	
	$.ws.link = function () {
		$.ws.obg = new WebSocket('ws://' + WS_HOST + ':'+ WS_PORT +'/');
		//alert('ws://' + WS_HOST + ':'+ WS_PORT +'/');
		$.ws.obg.onopen = function(){
			$.ws.status = true;
			$.each( $.ws.open,function( k, v ) {
				v.call(this);
			})
		};
		
		// 关闭
		$.ws.obg.onclose = function() {
			$.ws.status = false;
			$.each( $.ws.close,function( k, v ) {
				v.call(this);
			})
		};
		
		// 接收消息
		/*
		$.ws.obg.onmessage = function( msg ) {
			var d = $.parseJSON( msg.data );
			alert(msg.data);	//消息内容
			d = d || [];
			$.each( d,function( k, v ) {
				$.ws.message[k] = $.ws.message[k] || [];
				$.each( $.ws.message[k],function( kk, vv ) {
					vv.call( this, v );
				})
			})
		};
		*/
		$.ws.obg.onmessage = function( msg ) {
			//alert(msg.data);	//消息内容
			var data = $.parseJSON('['+msg.data+']');
			if(data[0].type == 'ping'){
				$.wssend('{"type":"pong"}');
			}else{
				alert(msg.data);	//消息内容
			}
			if(data[0].type == 'login'){//登录
				alert(data[0].message);
				/*if((data[0].message != '') && (data[0].message != undefined)){
					var da=$(".list ul").html();//获取html内容
					if(data[0].message != 'error'){
						if(da != ''){//登录信息累加
							$(".list ul").html(da+'<li>'+data[0].message+'登录成功</li>');
						}else{
							$(".list ul").html('<li>'+data[0].message+'登录成功</li>');
						}
						var name = $("#name").val();
						if(data[0].message == name){
							$.wssend('{"type":"tiqu"}');
							document.getElementById("left").style.display="block";
							document.getElementById("right").style.display="block";
						}
					}else{
						alert('登录失败');
					}
				}*/
			}
			if(data[0].type == 'liaot'){ //聊天
				if((data[0].content != '') && (data[0].content != undefined) && (data[0].content != 'error3')){
					var da=$(".message").html();
					var tp=data[0].content;
					var ppei=/\[[a-z]{1,2}:(.*?)\]/g;
					var arr=tp.match(ppei);
					var yzt=/\[[a-z]{1}_(.*?)\]/g;
					var zitiac=tp.match(yzt);
					if(zitiac!=null){
						for(var i=0;i<zitiac.length;i++){  
							var yanse=new RegExp('c_');
							var ziti=new RegExp('z_');
							if(yanse.test(zitiac[i])){    //颜色
								str =zitiac[i].split("[c_"); strs =str[1].split(']');
								data[0].content=data[0].content.replace(zitiac[i],'<span style="color:'+strs[0]+'">');	
								data[0].content = data[0].content.replace('[/c]','</span>');//替换字符串
							}else if(ziti.test(zitiac[i])){  //字体
								str =zitiac[i].split("[z_"); strs =str[1].split(']');
								data[0].content = data[0].content.replace(zitiac[i],'<span style="font-size:'+strs[0]+'px;">');	
								data[0].content = data[0].content.replace('[/z]','</span>');//替换字符串
							}
						}
					}
					if(arr!=null){
						for(var i=0;i<arr.length;i++){
							var tp=new RegExp('p:');
							var yp=new RegExp('iy:');
							var bq=new RegExp('b:');
							if(tp.test(arr[i])){     //视频
								str =arr[i].split("[p:"); strs =str[1].split(']');
								shuzubtp = '<img width="80" height="80" onclick=wbtanchu("'+strs[0]+'") class="f_l t_m_5 l_m_5 pointer" src="/photo.php?id='+strs[0]+'" style="cursor:pointer" />';
								data[0].content=data[0].content.replace(arr[i],shuzubtp);	
							}else if(yp.test(arr[i])){   //音乐
								str =arr[i].split("[iy:"); strs =str[1].split(']');					
								shuzubtp ='<a href="/file.php?id='+strs[0]+'"><img src="../moren/images/fujian/txt.png" width="27" height="27" title="下载附件" style="cursor:pointer"/></a>';
								data[0].content=data[0].content.replace(arr[i],shuzubtp);	
							}else if(bq.test(arr[i])){   //表情
								str =arr[i].split("[b:"); strs =str[1].split(']');
								
								shuzubtp ='<img width="21" height="21" src="../biaoqing/moren/'+strs[0]+'.png" />';
								data[0].content=data[0].content.replace(arr[i],shuzubtp);	
							}
						}
					}
					//neirong = data[0].content;
					if(data[0].qid != '' && data[0].qid != undefined){
						neirong = '群组【'+data[0].qtitle+'】的'+data[0].nicheng +'说：'+data[0].content;
					}else if(data[0].nicheng != '' && data[0].nicheng != undefined){
						neirong = data[0].nicheng +'说：'+data[0].content;
					}
					if(da != ''){
						$(".message").html(da+'<div >'+neirong+'&nbsp;'+data[0].time+'</div>');
					}else{
						$(".message").html('<div>'+neirong+'&nbsp;'+data[0].time+'</div>');
					}
				}else if(data[0].content == 'error3'){
					alert('请先登录账户');
				}else if(data[0].content == 'error4'){
					alert('请选择聊天对象');
				}else{
					alert('发送失败');
				}
			}
			if(data[0].type == 'tiqu'){//好友和群组列表
				var haoyou = data[0].content;	
				for(var i=0;i<haoyou.length;i++){
					 arr=haoyou[i];
					 var da=$(".haoyou").html();
					 $(".haoyou").html('<div >'+da+'<div onclick=zd("'+arr['nicheng']+'","'+arr['uid']+'")><img width="50" height="50"  src="/photo.php?id='+arr['touxiang']+'" style="cursor:pointer" /><div onclick=zd("'+arr['nicheng']+'","'+arr['uid']+'")>'+arr['nicheng']+'</div></div>'+'</div>');
				}
				var qun = data[0].qun;			
				for(var i=0;i<qun.length;i++){
					 aq=qun[i];
					 var daq=$(".qun").html();
					 $(".qun").html('<div >'+daq+'<div onclick=zdq("'+aq['title']+'","'+aq['id']+'")><img width="50" height="50"  src="/photo.php?id='+aq['touxiang']+'" style="cursor:pointer" /><div onclick=zdq("'+aq['title']+'","'+aq['id']+'")>'+aq['title']+'</div></div>'+'</div>');
				}
				/*var ren = data[0].ren;	
				for(var i=0;i<ren.length;i++){
					 arr=ren[i];
					 var da=$(".haoyou").html();
					 $(".haoyou").html('<div >'+da+'<div onclick=zd("'+arr['nicheng']+'","'+arr['uid']+'")><img width="50" height="50"  src="/photo.php?id='+arr['touxiang']+'" style="cursor:pointer" /><div onclick=zd("'+arr['nicheng']+'","'+arr['uid']+'")>'+arr['nicheng']+'</div></div>'+'</div>');
				}
				//var friends = data[0].content;//我的好友
				var friends = data[0].ren;//所有有昵称的用户
				$("#haoyou").html('');
				for(var i=0;i<friends.length;i++){
					 var hy=friends[i];
					 var z=$("#haoyou").html();
					 $("#haoyou").html(z+'<div style="width:180px;height:35px;" onclick=lt('+hy['uid']+',"'+escape(hy['nicheng'])+'",1)><img width="30" height="30" src="/photo.php?id='+hy['touxiang']+'" style="cursor:pointer;float:left;border-radius:50%" /><span style="float:left;width:98px;height:20px;margin:5px;cursor:pointer;overflow:hidden;">'+hy['nicheng']+'</span></div>');
				}
				var group = data[0].qun;//我的群组
				$("#qunzu").html('');
				for(var j=0;j<group.length;j++){
					 var qz=group[j];
					 var y=$("#qunzu").html();
					 $("#qunzu").html(y+'<div style="width:180px;height:35px;" onclick=lt('+qz['id']+',"'+escape(qz['title'])+'",2)><img width="30" height="30" src="/photo.php?id='+qz['logo']+'" style="cursor:pointer;float:left;border-radius:50%" /><span style="float:left;width:98px;height:20px;margin:5px;cursor:pointer;overflow:hidden;">'+qz['title']+'</span></div>');
				}*/
			}
			if(data[0].type == 'chat'){//聊天
				//alert(data[0].content);
				if((data[0].content != '') && (data[0].content != undefined)){
					if((data[0].content != 'wdx') && (data[0].content != 'bzx') && (data[0].content != 'wnr') && (data[0].content != 'cg') && (data[0].content != 'cw')){
						var newstr = data[0].content;//赋值给一个变量
						//图片处理
						var nr = newstr.split("[p:");//分离字符串（图片）
						for(var i=0;i<nr.length;i++){//替换图片
							var thtp=nr[i].split("]")[0];
							newstr = newstr.replace('[p:'+thtp+']','<img onclick=wbtanchu("'+thtp+'") style="cursor:pointer;margin-left:5px;" title="查看大图" src="/photo.php?id='+thtp+'&size=80">');//替换字符串
						}
						//音频处理
						var nriy = newstr.split("[iy:");//分离字符串（音频）
						for(var j=0;j<nriy.length;j++){//替换音频
							var thyp=nriy[j].split("]")[0];
							newstr = newstr.replace('[iy:'+thyp+']','<a href="/file.php?id='+thyp+'"><img style="cursor:pointer;margin-left:5px;" width="27" height="27" title="下载音频" src="../moren/images/fujian/amr.png"></a>');//替换字符串
						}
						//表情处理
						var nrbq = newstr.split("[b:");//分离字符串（表情）
						for(var k=0;k<nrbq.length;k++){//替换表情
							var thbq=nrbq[k].split("]")[0];//数据库取luj及id
							newstr = newstr.replace('[b:'+thbq+']','<img width="25" height="25" src="../biaoqing/moren/'+thbq+'">');//替换字符串
						}
						//字体大小处理
						var ztdx = newstr.split("[s_");
						if(ztdx.length > 1){
							var dx = ztdx[1].split("]");
							var siz = dx[0];//字体大小
							newstr = newstr.replace('[s_'+siz+']','');
							newstr = newstr.replace('[/s]','');
						}else{
							var siz = 14;
						}
						//字体颜色处理
						var ztys = newstr.split("[c_");
						if(ztys.length > 1){
							var ys = ztys[1].split("]");
							var colo = ys[0];//字体颜色
							newstr = newstr.replace('[c_'+colo+']','');
							newstr = newstr.replace('[/c]','');
						}else{
							var colo = '#000000';
						}
						//输出内容
						var da=$(".message").html();//获取聊天内容
						if(data[0].qid != '' && data[0].qid != undefined){
							//活动、投票、行程处理
							var hd = newstr.split("[tp:");
							if(hd.length > 1){
								var id = hd[1].split("]")[0];
								$.post('/qun/?act=qtoupiao&rmtype=qim',{id:id,qid:data[0].qid},function(ra){
									if(ra != ''){
										newstr = newstr.replace('[tp:'+id+']',ra);
									}
									newstr = '群组【'+data[0].qtitle+'】的'+data[0].nicheng +'说：'+newstr;
									if(da != ''){//聊天内容累加
										$(".message").html(da+'<div style="font-size:'+siz+'px;color:'+colo+';">'+newstr+'&nbsp;'+data[0].time+'</div>');
									}else{
										$(".message").html('<div style="font-size:'+siz+'px;color:'+colo+';">'+newstr+'&nbsp;'+data[0].time+'</div>');
									}
								});
							}else{
								newstr = '群组【'+data[0].qtitle+'】的'+data[0].nicheng +'说：'+newstr;
								if(da != ''){//聊天内容累加
									$(".message").html(da+'<div style="font-size:'+siz+'px;color:'+colo+';">'+newstr+'&nbsp;'+data[0].time+'</div>');
								}else{
									$(".message").html('<div style="font-size:'+siz+'px;color:'+colo+';">'+newstr+'&nbsp;'+data[0].time+'</div>');
								}
							}
						}else if(data[0].nicheng != '' && data[0].nicheng != undefined){
							newstr = data[0].nicheng +'说：'+newstr;
							if(da != ''){//聊天内容累加
								$(".message").html(da+'<div style="font-size:'+siz+'px;color:'+colo+';">'+newstr+'&nbsp;'+data[0].time+'</div>');
							}else{
								$(".message").html('<div style="font-size:'+siz+'px;color:'+colo+';">'+newstr+'&nbsp;'+data[0].time+'</div>');
							}
						}
					}else if(data[0].content == 'wdx'){
						alert('请选择聊天对象');
					}else if(data[0].content == 'bzx'){
						alert('请先登录账号');
					}else if(data[0].content == 'wnr'){
						alert('请输入内容');
					}else if(data[0].content == 'cg'){
						alert('发送成功');
					}else if(data[0].content == 'cw'){
						alert('服务器开小差了');
					}else{
						alert('发送失败');
					}
				}else{
					alert('没有内容');
				}
			}
			
		};
	};
	
	// 连接
	$.ws.link();
	
	/*
	// 关闭自动重新连接
	$.wsclose(function(){
		setTimeout( $.ws.link, 6000 );
	});
	
	
	// 定时 time
	$.wsopen(function(){
		//$.ws.time = setInterval( function(){ $.wssend( "time=ture" ); }, 30000 );
	});
	$.wsclose(function(){
		$.ws.time && clearInterval( $.ws.time );
	});
	*/
});